const pug = require('pug');

function pugViewsMiddleware({ compiler } = {}) {
    return (ctx, next) => {
        if (ctx.render) return next()
        ctx.response.render = ctx.render = async (pagePath, locals = {}) => {
            const state = Object.assign(locals, ctx.state || {})
            let fileBuf = compiler.outputFileSystem.readFileSync(compiler.outputPath + `/pages/${pagePath}.pug`)
            let htmlFn = pug.compile(fileBuf.toString(), state)
            ctx.type = 'text/html'
            ctx.body = htmlFn()
            // return render()
        }
        return next()
    }
}

module.exports = pugViewsMiddleware